import { defineStore } from "pinia";
import { getAuthButtonListApi, getAuthMenuListApi } from "@/api/modules/login";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList } from "@/utils";
import newList from "@/assets/json/authMenuList.json";
export const useAuthStore = defineStore({
  id: "geeker-auth",
  state: () => ({
    // 按钮权限列表
    authButtonList: {},
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: ""
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
  },
  actions: {
    // Get AuthButtonList
    async getAuthButtonList() {
      const { data } = await getAuthButtonListApi();
      this.authButtonList = data;
    },
    // Get AuthMenuList
    async getAuthMenuList() {
      //menuIds 获取当前菜单的管理权限
      const { data, menuIds } = await getAuthMenuListApi();
      //newList
      newList.data = data; // 替换原有数据
      // let result = [];
      // const useInfoId = JSON.parse(sessionStorage.getItem("useInfo"));
      // result = data;
      // if (useInfoId.userId == 1) {
      //   result = data; // 超级管理员直接返回所有菜单列表
      // } else {
      //   result = this.filterRoutes(authMenuList.data, menuIds); //递归去重
      // }
      this.authMenuList = data;
    },

    filterRoutes(routes, idlist) {
      return routes
        .filter(route => idlist.includes(route.id)) // 筛选出在 idlist 中的路由
        .map(route => {
          // 如果当前路由有 children，则递归处理 children
          if (route.children) {
            const filteredChildren = this.filterRoutes(route.children, idlist);
            return {
              ...route,
              children: filteredChildren.length > 0 ? filteredChildren : undefined // 只保留非空的 children
            };
          }
          return route;
        });
    },
    // Set RouteName
    async setRouteName(name) {
      this.routeName = name;
    }
  }
});
